//
//  CurriculumSignedVC.m
//  优学荟管理系统
//
//  Created by 星道 on 17/7/18.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "CurriculumSignedVC.h"
#import "ZYCourseAttendanceTowModel.h"
#import "CurriculumSignedCell.h"
#import "UploadSignInPictureView.h"
#import "CourseAddStudentVC.h"

@interface CurriculumSignedVC ()<UITableViewDelegate,UITableViewDataSource>
{
    IBOutlet UITableView *_TableView;
    IBOutlet UIButton *_AllSelectBtn;
}
/** 数据 */
@property (nonatomic, strong) NSMutableArray <ZYCourseAttendanceTowModel *>*DataArr;
/** 已签到的数据存放 */
@property (nonatomic, strong) NSMutableArray <ZYCourseAttendanceTowModel *>*dataSigned;

/**
 是否被全选
 */
@property (nonatomic, assign) BOOL AllSelect;
@end

@implementation CurriculumSignedVC

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title = @"签到";

    [_TableView registerNib:[UINib nibWithNibName:[CurriculumSignedCell description] bundle:nil] forCellReuseIdentifier:@"Cell"];

    [self RefreshData];

    self.navigationItem.rightBarButtonItem = self.IsTeacher ? nil:[[UIBarButtonItem alloc] initWithTitle:@"增加学生" style:(UIBarButtonItemStylePlain) target:self action:@selector(MgrAddStudent)];
}

#pragma mark - 网络请求
/**
 本页数据请求
 */
- (void)RefreshData
{
    [HUD showHUD];
    NSMutableDictionary *Dict = [NSMutableDictionary dictionary];
    [Dict setValue:self.ID forKey:@"lessonId"];
    [Dict setValue:self.IsTeacher ? @"getCourseRecord2":@"getCourseRecord" forKey:@"action"];
    [Dict setValue:@1 forKey:@"pageNumber"];
    self.IsTeacher ? nil:[Dict setValue:[AccountTool shareAccountTool].currentAccount.oid forKey:@"oid"];
    [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:Dict Success:^(id Obj) {
        NSLog(@"%@",LLBaseURL(@"yxhUser.do"));
        NSLog(@"%@",Dict);
        NSLog(@"%@",[AccountTool shareAccountTool].currentAccount.authCode);
        [HUD hideHUD];
        if ([Obj[@"code"] isEqualToNumber:@1000])
        {
            // 取模型
            NSArray *Arr = Obj[@"t"][@"dataList"];
            // 转对象
            [Arr enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

                ZYCourseAttendanceTowModel *Model = [[ZYCourseAttendanceTowModel alloc] init_ObjectForValue:obj];
                // 转对象并保存下来
                [self.DataArr addObject:Model];
                //将已签到的数据单独设置为3
                if ([Model.isSign isEqualToNumber:@2])
                {
                    Model.isSign = @3;
                    [self.dataSigned addObject:Model];
                }
            }];
            [_TableView reloadData];
            //排序，将所有已签到的放在下面
            [self.DataArr sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {

                ZYCourseAttendanceTowModel *Model1 = (ZYCourseAttendanceTowModel *)obj1;
                ZYCourseAttendanceTowModel *Model2 = (ZYCourseAttendanceTowModel *)obj2;

                NSInteger a = [Model1.isSign integerValue];
                NSInteger b = [Model2.isSign integerValue];

                if (a > b)
                {
                    return NSOrderedDescending;
                }
                else if (a < b)
                {

                    return NSOrderedAscending;
                }
                else
                {
                    return NSOrderedSame;
                }
            }];
        }
        else
        {
            [HUD hideHUD];
            [HUD showError:Obj[@"msg"]];
        }
    } Fail:^(NSError *Error) {
        [HUD hideHUD];
        [HUD showError:NetErr];
    }];
}




#pragma mark - 点击事件
/**
 单击了全选
 */
- (IBAction)ClickAllSelect:(UIButton *)sender
{
    [self MgrAllSelect:sender];
}

/**
 点击了确认
 */
- (IBAction)ClickSure:(UIButton *)sender
{
    self.Sure ();
}





#pragma mark - 处理事件
/**
 处理增加学生事件
 */
- (void)MgrAddStudent
{
    //实例化增加学生VC
    CourseAddStudentVC *VC = [[CourseAddStudentVC alloc] init];
    //课程ID值传递
    VC.lessonId = [self.ID stringValue];
    //推出
    [self.navigationController pushViewController:VC animated:YES];
    // 学生增加之后刷新本界面
    VC.RefreshStudent = ^ () {
        [self.DataArr removeAllObjects];
        [_TableView reloadData];
        //网络请求数据
        [self RefreshData];
    };
}

/**
 处理全选事件
 */
- (void)MgrAllSelect:(UIButton *)Button
{
    Button.selected = !Button.selected;
    // 状态互反
    [self.DataArr enumerateObjectsUsingBlock:^(ZYCourseAttendanceTowModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.isSign =  [obj.isSign isEqualToNumber:@3] ? @3:Button.selected == YES?@2:@1;
        
    }];
    [_TableView reloadData];
}

/**
 处理选择事件
 */
- (instancetype (^)(ZYCourseAttendanceTowModel *,UIButton *))MgrSelect {

    return  ^(ZYCourseAttendanceTowModel *Model,UIButton *Button) {

        Button.selected = !Button.selected;
        Model.isSign = Button.selected?@2:@1;
        // 判断是否全选
        [self.DataArr enumerateObjectsUsingBlock:^(ZYCourseAttendanceTowModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            _AllSelect = [obj.isSign isEqualToNumber:@2] ? YES:NO;
            *stop = !_AllSelect;
        }];
        _AllSelectBtn.selected = _AllSelect;
        return self;
    };
}

/**
 缺勤
 */
- (IBAction)clickAbsenceBtn:(UIButton *)sender {
    
    //临时保存已中状态的对的模型ID
    NSMutableArray *IDArr = [NSMutableArray array];
    NSMutableArray *EnrollInfoIdArr = [NSMutableArray array];
    //挑选ID
    [self.DataArr enumerateObjectsUsingBlock:^(ZYCourseAttendanceTowModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        [obj.isSign isEqualToNumber:@2]?[IDArr addObject:[obj.user_ID stringValue]]:nil;
        [obj.isSign isEqualToNumber:@2]?[EnrollInfoIdArr addObject:[obj.enrollInfoId stringValue]]:nil;
    }];
    
    // 条件判断
    if (self.DataArr.count > 0 && self.DataArr.count == self.dataSigned.count) {
        
        [HUD showSuccess:@"没有需要登记缺勤的学生"];
    } else if (self.DataArr.count > 0 && IDArr.count == 0) {
        
        [HUD showError:@"请选择学生进行缺勤记录"];
    } else if (self.DataArr.count == 0) {
        
        [HUD showError:@"暂无学生报名该课程"];
    } else {
        
        [HUD showHUD];
        //得到最终IDArr后转成字符串
//        NSString *IDStr = [IDArr componentsJoinedByString:@","];
        NSString *EnrollInfoId = [EnrollInfoIdArr componentsJoinedByString:@","];
        // http://192.168.0.226:8080/StarShine/ys/yxhUser.do?action=saveAbsenteeism&uids=&lessonId=&status=&enrollInfoIds=
        NSString  *url  = [NSString stringWithFormat:@"yxhUser.do?action=saveAbsenteeism&lessonId=%@&status=1&enrollInfoIds=%@",[self.ID stringValue],EnrollInfoId];
         NSLog(@"%@  %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);
        [NetManager Get:LLBaseURL(url) Auth:YES Params:nil Success:^(id Obj) {
            [HUD hideHUD];
            if ([[Obj valueForKey:@"code"] integerValue] == 1000) {
                
                
                NSArray *IDArr = [EnrollInfoId componentsSeparatedByString:@","];
                [IDArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    NSString *ID = obj;
                    [self.DataArr enumerateObjectsUsingBlock:^(ZYCourseAttendanceTowModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        //匹配条件
                        if ([ID isEqualToString:[obj.enrollInfoId stringValue]]) {
                            obj.todayAbsence = @"1";
                            
                        }
                    }];
                }];
                [HUD showSuccess:@"登记缺勤成功"];
                [_TableView reloadData];
                
            } else {
                [HUD hideHUD];
                [HUD showError:Obj[@"msg"]];
            }
            
        } Fail:^(NSError *Error) {
            [HUD hideHUD];
            [HUD showError:NetErr];
            
        }];
        
        
    }
    
    
    
}



/**
 请假
 */
- (IBAction)clickOnHolidayBtn:(id)sender {
    
    //临时保存已中状态的对的模型ID
    NSMutableArray *IDArr = [NSMutableArray array];
    NSMutableArray *EnrollInfoIdArr = [NSMutableArray array];
    //挑选ID
    [self.DataArr enumerateObjectsUsingBlock:^(ZYCourseAttendanceTowModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        [obj.isSign isEqualToNumber:@2]?[IDArr addObject:[obj.user_ID stringValue]]:nil;
        [obj.isSign isEqualToNumber:@2]?[EnrollInfoIdArr addObject:[obj.enrollInfoId stringValue]]:nil;
        
    }];
    
    // 条件判断
    if (self.DataArr.count > 0 && self.DataArr.count == self.dataSigned.count) {
        
        [HUD showSuccess:@"没有需要登记请假的学生"];
    } else if (self.DataArr.count > 0 && IDArr.count == 0) {
        
        [HUD showError:@"请选择学生进行缺勤记录"];
    } else if (self.DataArr.count == 0) {
        
        [HUD showError:@"暂无学生报名该课程"];
    } else {
        
        [HUD showHUD];
        
        //得到最终IDArr后转成字符串
//        NSString *IDStr = [IDArr componentsJoinedByString:@","];
        NSString *EnrollInfoId = [EnrollInfoIdArr componentsJoinedByString:@","];
        // http://192.168.0.226:8080/StarShine/ys/yxhUser.do?action=saveAbsenteeism&uids=&lessonId=&status=&enrollInfoIds=
        
        NSString  *url  = [NSString stringWithFormat:@"yxhUser.do?action=saveAbsenteeism&lessonId=%@&status=2&enrollInfoIds=%@",[self.ID stringValue],EnrollInfoId];
        NSLog(@"%@  %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);
        [NetManager Get:LLBaseURL(url) Auth:YES Params:nil Success:^(id Obj) {
            [HUD hideHUD];
            
            if ([[Obj valueForKey:@"code"] integerValue] == 1000) {
                NSArray *IDArr = [EnrollInfoId componentsSeparatedByString:@","];
                [IDArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    NSString *ID = obj;
                    [self.DataArr enumerateObjectsUsingBlock:^(ZYCourseAttendanceTowModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        //匹配条件
                        if ([ID isEqualToString:[obj.enrollInfoId stringValue]]) {
                            obj.todayAbsence = @"1";
                            
                        }
                    }];
                }];
                [HUD showSuccess:@"登记请假成功"];
                [_TableView reloadData];
                
            } else {
                [HUD hideHUD];
                [HUD showError:Obj[@"msg"]];
            }
            
            
        } Fail:^(NSError *Error) {
            [HUD hideHUD];
            [HUD showError:NetErr];
        }];
    
        
    }

}



/**
 实现提交方法
 */
- (instancetype (^)())Sure {

    return ^() {

        //临时保存已中状态的对的模型ID
        NSMutableArray *IDArr = [NSMutableArray array];
        NSMutableArray *EnrollInfoIdArr = [NSMutableArray array];
        //挑选ID
        [self.DataArr enumerateObjectsUsingBlock:^(ZYCourseAttendanceTowModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

            //符合就加入豪华晚餐
            [obj.isSign isEqualToNumber:@2]?[IDArr addObject:[obj.user_ID stringValue]]:nil;
            [obj.isSign isEqualToNumber:@2]?[EnrollInfoIdArr addObject:[obj.enrollInfoId stringValue]]:nil;

        }];

        // 条件判断
        if (self.DataArr.count > 0 && self.DataArr.count == self.dataSigned.count) {
  
            [HUD showSuccess:@"所有的学生已签到"];
        } else if (self.DataArr.count > 0 && IDArr.count == 0) {

            [HUD showError:@"请选择学生进行签到"];
        } else if (self.DataArr.count == 0) {

            [HUD showError:@"暂无学生报名该课程"];
        } else {

            //得到最终IDArr后转成字符串
            NSString *IDStr = [IDArr componentsJoinedByString:@","];
            NSString *EnrollInfoId = [EnrollInfoIdArr componentsJoinedByString:@","];

            // 提交相片及数据
            [UploadSignInPictureView UploadSignInPictureView_ConfigViewWithLessonId:[self.ID stringValue] Uids:IDStr enrollInfoIds:EnrollInfoId Complete:^{
                //签到成功，则将数组里的isSign全部设为3
                //将IDStr重新返回数组
                NSArray *IDArr = [EnrollInfoId componentsSeparatedByString:@","];
                [IDArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

                    NSString *ID = obj;
                    [self.DataArr enumerateObjectsUsingBlock:^(ZYCourseAttendanceTowModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        //匹配条件
                        if ([ID isEqualToString:[obj.enrollInfoId stringValue]]) {
                            obj.isSign = @3;
                            // 将上课次数首位提取出来
                            NSInteger first = [[[obj.record componentsSeparatedByString:@"/"] firstObject] integerValue];
                            NSInteger last = [[[obj.record componentsSeparatedByString:@"/"] lastObject] integerValue];
                            first += 1;
                            obj.record = [NSString stringWithFormat:@"%ld/%ld",first,last];

                        }
                    }];
                }];
                [_TableView reloadData];
            }];
        }
        return self;
    };
}
#pragma mark - TableView代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.DataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 取对象
    ZYCourseAttendanceTowModel *Model = self.DataArr[indexPath.row];
    // 实例化
    CurriculumSignedCell *Cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    // 点语法
    Cell.Model (Model);
    //单击了选择
    Cell.ClickSelect = ^(UIButton *Button){

        self.MgrSelect(Model,Button);
    };

    return Cell;
}

#pragma mark - Setter
- (NSMutableArray<ZYCourseAttendanceTowModel *> *)DataArr
{
    if (!_DataArr)
    {
        _DataArr = [NSMutableArray array];
    }
    return _DataArr;
}


- (NSMutableArray<ZYCourseAttendanceTowModel *> *)dataSigned {

    if (!_dataSigned)
    {
        _dataSigned = [NSMutableArray array];
    }
    return _dataSigned;
}
@end
